
from typing import List, Optional, Any
from datetime import datetime, date
import json

from {{ base_module }} import BaseModel

class {{ class_name }}(BaseModel):
    """
    {{ table_name }} 表的映射类
    """

    {% for field in fields %}
    @property
    def {{ field.name }}(self) -> {{ field.type }}:
        """{{ field.comment or field.name }}"""
        return self._{{ field.name }}

    @{{ field.name }}.setter
    def {{ field.name }}(self, value: {{ field.type }}):
        self._{{ field.name }} = value
    {% endfor %}

    def __init__(self{% for field in fields %}, {{ field.name }}: {{ field.type }} = None{% endfor %}):
        """初始化{{ class_name }}实例"""
        super().__init__()
        {% for field in fields %}
        self._{{ field.name }} = {{ field.name }}
        {% endfor %}

    def to_dict(self) -> dict:
        """将对象转换为字典"""
        return {
            {% for field in fields %}
            "{{ field.name }}": self.{{ field.name }}{% if not loop.last %},{% endif %}{% endfor %}
        }

    @classmethod
    def from_dict(cls, data: dict) -> '{{ class_name }}':
        """从字典创建对象"""
        return cls(
            {% for field in fields %}
            {{ field.name }}=data.get("{{ field.name }}"){% if not loop.last %},{% endif %}{% endfor %}
        )

    def to_json(self) -> str:
        """将对象转换为JSON字符串"""
        return json.dumps(self.to_dict(), default=str)

    @classmethod
    def from_json(cls, json_str: str) -> '{{ class_name }}':
        """从JSON字符串创建对象"""
        data = json.loads(json_str)
        return cls.from_dict(data)

    def __str__(self) -> str:
        # 手动构建字段字符串
        field_strings = []
        {% for field in fields %}
        field_strings.append("{{ field.name }}=" + str(self._{{ field.name }}))
        {% endfor %}
        return "{{ class_name }}(" + ", ".join(field_strings) + ")"

    def __repr__(self) -> str:
        return self.__str__()
